package org.sidora.strata.explorer;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Category;
import org.sidora.core.Feature;
import org.sidora.core.Sector;
import org.sidora.core.context.Context;
import org.sidora.core.util.AbstractInventory;
import org.sidora.core.util.LoggerProvider;
import org.sidora.core.util.ParameterCollector;
import org.sidora.strata.SidoraTools;
import org.sidora.strata.Storage;


/**
 * Context Explorer Form
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class ContextExplorerTopComponent extends TopComponent {
    
    private static ContextExplorerTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "ContextExplorerTopComponent";
    
    private ContextExplorerTopComponent() {
        System.setProperty(
            "Quaqua.tabLayoutPolicy","wrap"
         );
         // set the Quaqua Look and Feel in the UIManager
         try { 
              UIManager.setLookAndFeel(
                  "ch.randelshofer.quaqua.QuaquaLookAndFeel"
              );
         // set UI manager properties here that affect Quaqua
         
         } catch (Exception e) {
             // take an appropriate action here
             
         }
         // insert your application initialization code here
         
        initComponents();
        setName(NbBundle.getMessage(ContextExplorerTopComponent.class, "CTL_ContextExplorerTopComponent"));
        setToolTipText(NbBundle.getMessage(ContextExplorerTopComponent.class, "HINT_ContextExplorerTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jListContext = new javax.swing.JList();
        jListContext.putClientProperty(
            "Quaqua.List.style", "striped"
        );
        jButtonDelFeature = new javax.swing.JButton();
        jButtonDelFeature.putClientProperty(
            "Quaqua.Button.style","square"
        );
        jButtonDelFeature1 = new javax.swing.JButton();
        jButtonDelFeature1.putClientProperty(
            "Quaqua.Button.style","square"
        );

        jListContext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListContextMouseClicked(evt);
            }
        });
        jListContext.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListContextValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jListContext);

        org.openide.awt.Mnemonics.setLocalizedText(jButtonDelFeature, "-");
        jButtonDelFeature.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelFeatureActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButtonDelFeature1, "+");
        jButtonDelFeature1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelFeature1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(82, Short.MAX_VALUE)
                .add(jButtonDelFeature1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButtonDelFeature))
        );

        layout.linkSize(new java.awt.Component[] {jButtonDelFeature, jButtonDelFeature1}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonDelFeature)
                    .add(jButtonDelFeature1)))
        );

        layout.linkSize(new java.awt.Component[] {jButtonDelFeature, jButtonDelFeature1}, org.jdesktop.layout.GroupLayout.VERTICAL);

    }// </editor-fold>//GEN-END:initComponents
    
    private void jListContextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListContextMouseClicked
            }//GEN-LAST:event_jListContextMouseClicked
    
    private void jListContextValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListContextValueChanged
        SidoraTools.showElement();
        Storage.getContextFormAction().saveFields();
        Storage.setContext((Context) jListContext.getSelectedValue());
        Storage.getContextFormAction().actionPerformedShow();
        Storage.getDocsPropertiesAction().actionPerformed();
        Storage.getStrataPropertiesAction().actionPerformed();
        /*
        if (jListContext.getValueIsAdjusting()){
            SidoraTools.showElement();
            Storage.getContextFormAction().saveFields();
            Storage.setContext((Context) jListContext.getSelectedValue());
            Storage.getContextFormAction().actionPerformedShow();
            Storage.getDocsPropertiesAction().actionPerformed();
            Storage.getStrataPropertiesAction().actionPerformed();
        }*/
    }//GEN-LAST:event_jListContextValueChanged
    
    private void jButtonDelFeature1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelFeature1ActionPerformed
        addContext();
        fillContextItems();
    }//GEN-LAST:event_jButtonDelFeature1ActionPerformed
    
    private void jButtonDelFeatureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelFeatureActionPerformed
        delContext();
    }//GEN-LAST:event_jButtonDelFeatureActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDelFeature;
    private javax.swing.JButton jButtonDelFeature1;
    private javax.swing.JList jListContext;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    private static Context.Inventory conti = new Context.Inventory();
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized ContextExplorerTopComponent getDefault() {
        if (instance == null) {
            instance = new ContextExplorerTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the ContextExplorerTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ContextExplorerTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find ContextExplorer component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ContextExplorerTopComponent) {
            return (ContextExplorerTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        this.setDisplayName("Context");
    }
    
    public void componentClosed() {
        // TODO add custom code on component closing
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return ContextExplorerTopComponent.getDefault();
        }
    }
    
    public void fillContextItems(){
        Feature feature = Storage.getFeature();
        Sector sector = Storage.getSector();
        
        if (feature != null || sector != null){
            DefaultListModel contextModel = new DefaultListModel();
            
            try {
                List list;
                if (feature != null){
                    list = Context.Inventory.getList(feature);
                }else if (sector != null && feature == null){
                    list = Context.Inventory.getList(sector);
                }else{
                    throw new RuntimeException();
                }
                
                TreeSet <Context> contexts = new TreeSet<Context>(list);
                
                //Iterator iter2 = list.iterator();
                //while(iter2.hasNext()){
                //    Context context = (Context) iter2.next();
                //    contexts.add(context);
                //}
                
                Iterator iter = contexts.iterator();
                //Iterator iter = list.iterator();
                while (iter.hasNext()){
                    contextModel.addElement(iter.next());
                }
                
            } catch (Exception e1) {
                LoggerProvider.getInstance().log(Level.WARNING,"Exception",e1);
            }
            jListContext.setModel(contextModel);
        } else {
            jListContext.setModel(new DefaultListModel());
        }
    }
    
    private static void addContext(){
        //Fem sortir un JOptinPane per a obtenir el tipus de context
        String input = null;
        TopComponent win = Storage.getContextFormAction().getTopComponent();
        
        
        String options[] = {"Stratum", "Builded", "Emptyed","Surface","Devastated","Deposed","Technical"};
        input = (String)JOptionPane.showInputDialog(win,"Select Context type","New Context",JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
        
        if (input == null)
            return;
        
        ParameterCollector param = new ParameterCollector();
        
        param.put("zone", Storage.getZone());
        param.put("feature", Storage.getFeature());
        param.put("sector",Storage.getSector());
        param.put("type", input);
        param.put("action",Storage.getSite().getDefaultAction());
        
        Context context = null;
        try {
            //nou = (Context) InventoryPool.getInventory("Context").getNewObject(param);
            context = (Context) conti.getNewObject(param);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        conti.setObject(context);
    }
    
    private void delContext() {
        Context context = (Context) jListContext.getSelectedValue();
        AbstractInventory.deleteObject(context);
        fillContextItems();
        Storage.setContext(null);
    }
    
}
